package com.cracker.sso.controller;

import com.cracker.sso.dto.request.LoginDto;
import com.cracker.sso.dto.request.RegisterDto;
import com.cracker.sso.dto.response.UserDto;
import com.cracker.sso.service.UserService;
import com.cracker.sso.vo.LoginVO;
import com.cracker.sso.vo.RegisterSuccessVO;
import com.cracker.sso.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("login")
    public String login(ModelMap view, @RequestParam(name = "oauth_callback") String redirect, HttpServletRequest request, HttpServletResponse response) throws IOException {
        LoginVO vo = new LoginVO();
        vo.setLoginDto(new LoginDto());
        vo.setLoginUrl("/user/doLogin?oauth_callback=" + redirect);
        vo.setRegisterUrl("/user/register?oauth_callback=" + redirect);
        view.addAttribute("vo", vo);
        view.addAttribute("login", vo.getLoginDto());
        return "user/login";
    }

    @PostMapping("doLogin")
    public void doLogin(@RequestParam(name = "oauth_callback") String redirect, @ModelAttribute LoginDto loginDto, HttpServletResponse response) throws IOException {
        UserDto userDto = userService.login(loginDto);
        response.sendRedirect(String.format("%s?token=%s", redirect, userDto.getToken()));
    }

    @GetMapping("register")
    public String register(ModelMap view, @RequestParam(name = "oauth_callback") String redirect, HttpServletRequest request, HttpServletResponse response) throws IOException {
        RegisterVO registerVO = new RegisterVO();
        registerVO.setRegisterDto(new RegisterDto());
        registerVO.setLoginUrl("/user/login?oauth_callback=" + redirect);
        registerVO.setRegisterUrl("/user/doRegister?oauth_callback=" + redirect);
        view.addAttribute("vo", registerVO);
        view.addAttribute("form", registerVO.getRegisterDto());
        return "user/register";
    }

    @PostMapping("doRegister")
    public String doRegister(ModelMap view, @RequestParam(name = "oauth_callback") String redirect, @ModelAttribute RegisterDto registerDto, HttpServletRequest request, HttpServletResponse response) throws IOException {
        UserDto userDto = userService.register(registerDto);
        RegisterSuccessVO vo = new RegisterSuccessVO();
        vo.setUserDto(userDto);
        vo.setMessage("注册成功");
        vo.setRedirect(redirect);
        view.addAttribute("vo", vo);
        return "user/register_success";
    }
}
